//
//  ContentView.swift
//  macOS截屏
//
//  Created by apple on 2021/6/15.
//

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, World!")
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .onTapGesture {
                    takeScreenShots(folderName: "234")
                }
        }
        
//        ScrernShotsView.initialize()
    }
    
    //电脑全屏截图
    func takeScreenShots(folderName: String) {
        var displayCount: UInt32 = 0
        var result = CGGetActiveDisplayList(0, nil, &displayCount)
        if result != CGError.success {
            print("error: \(result)")
            return
        }
        let allocated = Int(displayCount)
        let activeDisplays = UnsafeMutablePointer<CGDirectDisplayID>.allocate(capacity: allocated)
        result = CGGetActiveDisplayList(displayCount, activeDisplays, &displayCount)
        
        if result != CGError.success {
            print("error: \(result)")
            return
        }
        for i in 1...displayCount {
                let unixTimestamp = CreateTimeStamp()
                let fileUrl = URL(fileURLWithPath: folderName + "\(unixTimestamp)" + "_" + "\(i)" + ".jpg", isDirectory: true)
                let screenShot:CGImage = CGDisplayCreateImage(activeDisplays[Int(i-1)])!
                let bitmapRep = NSBitmapImageRep(cgImage: screenShot)
            print("\(fileUrl)")
            let jpegData = bitmapRep.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])!

                do {
                    try jpegData.write(to: fileUrl, options: .atomic)
                }
                catch {print("error: \(error)")}
            }
    }
    
    //指定区域截屏
    
    func CreateTimeStamp() -> Int32 {
        return Int32(Date().timeIntervalSince1970)
    }
}

extension NSView {
    func saveSelfAsImage(){

        let image = NSImage(data: self.dataWithPDF(inside: self.bounds))
        let imageData = image!.tiffRepresentation
        let fileManager = FileManager.default
        //制定文件路径
        let path = "/Users/.../Documents/myCapture.png"
        fileManager.createFile(atPath: path, contents: imageData, attributes: nil)
        //保存结束后Finder中自动定位到文件路径
        let fileUrl = URL(fileURLWithPath: path)
        print("\(fileUrl)")
        NSWorkspace.shared.activateFileViewerSelecting([fileUrl])
    }
    
    func save(){
        self.lockFocus()
        let image = NSImage(data: self.dataWithPDF(inside: self.bounds))
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
